package softtech.apps.autoanswerphonecall;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import softtech.apps.model.Config;
import softtech.apps.model.Contact;
import softtech.apps.model.DatabaseHandler;
import softtech.apps.model.RowRecord;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v4.app.NotificationCompat;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;

public class PhoneReceiver extends BroadcastReceiver{

	public static final String LISTEN_ENABLED = "ListenEnabled";
	public static final String FILE_DIRECTORY = "softtech";
	private String phoneNumber;
	public static final int STATE_INCOMING_NUMBER = 0;
	public static final int STATE_CALL_START = 1;
	public static final int STATE_CALL_END = 2;
	DatabaseHandler db;
	private static List<Config> cfg;
	
	String tag = "TAG";
	private List<Contact> listContact;
	private List<Contact> blackList;
	int mType;
	private static String mPhoneNumber;
	private static boolean incomingFlag = true;
	
	public PhoneReceiver() {
		// TODO Auto-generated constructor stub
		listContact = new ArrayList<Contact>();
		blackList = new ArrayList<Contact>();
	}

	@Override
	public void onReceive(final Context context, Intent intent) {
		// TODO Auto-generated method stub
		SharedPreferences settings = context.getSharedPreferences(LISTEN_ENABLED, 0);
		boolean silent = settings.getBoolean("silentMode", true);
		phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
		 if (intent.getAction().equals (Intent.ACTION_NEW_OUTGOING_CALL)) {
			 incomingFlag = false; 
		 }
		 Log.d("INCOMMING", "Flag = "+incomingFlag);
        db = new DatabaseHandler(context);
        cfg = db.getAllConfigs();
        db.close();
        Config cc = cfg.get(0); // Enable/Disable app
        Config aq = cfg.get(1); // type to reply
        // Get config to select default record file here
        Config cfgType = cfg.get(4); // receive voice message
        Config cfgReceiveVoiceMessage = cfg.get(5);
        Config cfgDelayTime = cfg.get(6);
        RowRecord audio_path = db.getNameRecordDefault(); 
        mType = cfgType.get_value();
        blackList = db.getContactsByType(mType);
        getContacts(context);
//		Log.d("CONTACT", "Contact size = "+listContact.size());
//		Log.d("CONTACT", "Blacklist size = "+blackList.size());
        
        // Check current Task today
        boolean check = db.checkTimer();
        Log.d("TASK", "Task co duoc thuc hien hay khong ="+check);
        // Check mounted SdCard
		boolean mounted = false;
		if((MainActivity.updateExternalStorageState() == MainActivity.MEDIA_MOUNTED)){
			mounted = true;
		}
		Log.d("MOUNTED","Gia tri so sanh duoc ="+mounted);
		if (silent && cc.get_value()==1 && mounted && check)
		{
			Log.d(tag, "Phone number = "+phoneNumber);
			if(phoneNumber != null){
				mPhoneNumber = phoneNumber;
			}
			if (phoneNumber == null)
			{
				if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) 
				{
					
						Log.d(tag,"############# OFFHOOK STATE");
						Log.d(tag, "Phone number in Offhook = "+mPhoneNumber);
						// Check black list here
						boolean isOK = false;
						if(mType == 0){
							isOK = !checkBlackList(blackList,mPhoneNumber);
						}else if(mType==1){
							isOK = !checkBlackList(blackList,mPhoneNumber) && checkContact(listContact,phoneNumber);
						}else{
							isOK = checkBlackList(blackList,mPhoneNumber) && !checkContact(listContact,phoneNumber);
						}
						int typeReply = aq.get_value();
						if(isOK && typeReply == 1){
							Log.d("OK", "##################### OK");
							Intent myIntent = new Intent(context, PhoneRecordService.class);
							myIntent.putExtra("commandType", STATE_CALL_START);
							myIntent.putExtra("phoneNumber",  mPhoneNumber);
							myIntent.putExtra("incomingFlag",  incomingFlag);
							myIntent.putExtra("audio_name",  audio_path.getmFileName());
							myIntent.putExtra("audio_path",  audio_path.getmFilePath());
							int isRecoding = cfgReceiveVoiceMessage.get_value();
							myIntent.putExtra("isRecord",isRecoding);
							context.startService(myIntent);
						}
					
				}
				else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)) 
				{
					
					Log.d(tag,"#############Ket thuc cuoc goi");
					Log.d(tag, "Phone number in Ket thuc = "+phoneNumber);
					Intent myIntent = new Intent(context, PhoneRecordService.class);
					myIntent.putExtra("commandType", STATE_CALL_END);
					context.startService(myIntent);
					Log.d("MESSAGE", "Gia type send message from database = "+aq.get_value());
					if(aq.get_value()==0){
						// Send SMS here
						Log.d("MESSAGE", "Se gui text message cho nguoi goi !!");
						softtech.apps.model.Message mes = new softtech.apps.model.Message();
						mes = db.getMessageDefault();
						SmsManager smsManager = SmsManager.getDefault();
						smsManager.sendTextMessage(mPhoneNumber, null, mes.get_content(), null, null);
						 NotificationCompat.Builder mBuilder =
						            new NotificationCompat.Builder(context)
						            .setSmallIcon(R.drawable.ic_launcher)
						            .setContentTitle("Note from Auto Answer Phone Call")
						            .setContentText("Just send a text message to "+mPhoneNumber);

						        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
						        mNotificationManager.notify(1, mBuilder.build());
					}
					
				}
				else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) 
				{
					Log.d(tag,"######### Bat dau do chuong");
					if (phoneNumber == null)
						phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
					
					if(phoneNumber!=null){
						mPhoneNumber = phoneNumber;
					}
					Log.d(tag, "Phone number in Ringing = "+mPhoneNumber);
					
					// Accept a call here and play sound before recorded
					// Accept a call with delay time
					Intent myIntent = new Intent(context, PhoneRecordService.class);
					myIntent.putExtra("commandType", STATE_INCOMING_NUMBER);
					myIntent.putExtra("phoneNumber",  phoneNumber);
					context.startService(myIntent);
					
					// Delay time before accept a call
					int delayTime = cfgDelayTime.get_value();
					Log.d("DELAYTIME", "Delay time = "+delayTime);
					if(incomingFlag && aq.get_value()==1){
						 new Handler().postDelayed(new Runnable() {
				                public void run() {
				                	acceptCall(context); // tu dong bat may de tra loi
				                }
				            }, delayTime * 1000);
					}
				}
			}
			else
			{
				
					Intent myIntent = new Intent(context, PhoneRecordService.class);
					myIntent.putExtra("commandType", TelephonyManager.EXTRA_INCOMING_NUMBER);
					myIntent.putExtra("phoneNumber",  phoneNumber);
					context.startService(myIntent);
				
			}
			
		}
	}
	
	public boolean checkBlackList(List<Contact> blackList,String phoneNum){
		if(phoneNum==null || phoneNum.equals(null) || phoneNum.equals("") || phoneNum.trim().length()<=0)
			return false;
		for(Contact contact: blackList){
        	if(contact.get_phone_number().contains(phoneNum)){
        		//Log.d("BLACKLIST","Thoi xong nam trong black list CMNR");
        		return true;
        	}
        }
		return false;
	}
	
	public boolean checkContact(List<Contact> contactList,String phoneNum){
		if(phoneNum.equals("") || phoneNum.equals(null) || phoneNum == "")
			return false;
		for(Contact contact: contactList){
        	if(contact.get_phone_number().contains(phoneNum)){
        		//Log.d("BLACKLIST","Thoi xong nam trong contact list CMNR");
        		return true;
        	}
        }
		return false;
	}
	public void getContacts(Context context) {
		// Get all contact here
		ContentResolver cr = context.getContentResolver();
		Cursor cur = cr.query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
				null, null);
		cur.moveToFirst();

		while (cur.moveToNext()) {
			String contactId = cur.getString(cur
					.getColumnIndex(ContactsContract.Contacts._ID));

			// Log.e("contact id"," contact id="+contactId);

			String name = cur
					.getString(cur
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

			// String
			// phone=cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

			String hasPhone = null;

			int hasphone = -1;
			try {
				hasPhone = cur
						.getString(cur
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
				hasphone = Integer.parseInt(hasPhone);
				// Log.e("contactID",contactId);
			} catch (Exception ex) {

				// Log.e("contactID",contactId);
			}

			if (hasphone > 0) {
				// Log.d("CONTACT", "Has phone number from SIM CARD");
				String phone = cur
						.getString(cur
								.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				Contact ct = new Contact(name, phone, contactId,0);
				listContact.add(ct);
			} else {

			}

			Comparator<Contact> a = new Comparator<Contact>() {

				@Override
				public int compare(Contact lhs, Contact rhs) {
					// TODO Auto-generated method stub
					return lhs.get_name().compareTo(rhs.get_name());
				}
			};

			Collections.sort(listContact, a);
		}
	}
	
	// Accept an incoming call
	public static void acceptCall(Context context) {
		Log.d("ACCEPT", "Accepted a call");
		Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);
		buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(
				KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
		context.sendOrderedBroadcast(buttonDown,
				"android.permission.CALL_PRIVILEGED");

		// froyo and beyond trigger on buttonUp instead of buttonDown
		Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
		buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(
				KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
		context.sendOrderedBroadcast(buttonUp,
				"android.permission.CALL_PRIVILEGED");
	}
	
}
